'use strict';

angular.module('backofficeApp.backendUser.controllers',[]).
    controller('backendUserCtrl',['$scope','$location','$filter','$http','backendUserCommunityService','backendUserService','$routeParams','getAllUnbindedServiceUser',
        function($scope,$location,$filter,$http,backendUserCommunityService,backendUserService,$routeParams,getAllUnbindedServiceUser){

        $scope.$watch('$viewContentLoaded', function () {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/100', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $scope.backendUserList = result.data.items;
            }).error(function () {
            });
        });

        var selectMenu ={
            create:function(data,select){
                for(var i in data)
                {
                    var option=data[i];
                    if(option&&option.objId&&option.communityName) {
                        var value = option.objId;
                        var text = option.communityName;
                        this.menu.append("<option "+select+" value='" + value + "'>" + text + "</option>");
                    }

                }
            },
            clear:function(){
                this.menu.children().remove();
            },
            getValue:function(){
                var communities=[];
                this.menu.find("option:selected").each(function(){
                    communities.push($(this).val());
                });
                return communities;
            }
        };

        var userMenu ={
            create:function(data, selected){
                for(var i in data)
                {
                    var option=data[i];
                    if(option&&option.objId&&option.mobilePhone) {
                        var value = option.objId;
                        var text = option.mobilePhone;
                        this.menu.append("<option "+selected+" value='" + value + "'>" + text + "</option>");
                    }

                }
            },
            clear:function(){
                this.menu.children().remove();
            },
            getValue:function(){
                var communities=[];
                this.menu.find("option:selected").each(function(){
                    communities.push($(this).val());
                });
                return communities;
            }
        };
        var serviceStr="Service"
        //===========================================================
        $scope.onRoleChange=function(status){
                            if (value === status) {
                                role_select.show()
                            }
                            else {
                                role_select.hide()
                            }
        }
        $scope.addUser=function(){
            $('#user_modal').modal('show');
            backendUserCommunityService.get(function(res){
                selectMenu.menu=$('#communities_select');
                selectMenu.clear();
                selectMenu.create(res.data,"");
            });


            getAllUnbindedServiceUser.get(function(res){
                userMenu.menu=$('#user_select');
                userMenu.clear();
                userMenu.create(res.data,"");
            });

            $scope.backendUser=null;
            $scope.popupTitle = "Create a new backend User...";
            $("#loginId").prop('disabled', false);
            $('#saveButton').show();
            $('#updateButton').hide();

        };
        $scope.saveAdd=function(backendUser){
            if(backendUser.password!=backendUser.password2){
                $scope.matchFlag=false;
                return;
            }
            selectMenu.menu=$('#communities_select');
            backendUser.communities=selectMenu.getValue();
            userMenu.menu=$('#user_select');
            if(userMenu.getValue().length==1){
                backendUser.appuser=userMenu.getValue()[0]
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser', backendUser, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                var isFreshlist=true;
                if(data.result.status==1) {
                    if (data.data.role === "Service" && !data.data.appuser) {
                        isFreshlist=false;
                        backendUserService.get({serviceId: data.data.objId}, function (res) {
                            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/20', {
                                headers: {'Content-Type': 'application/json;charset=utf-8'}
                            }).success(function (result) {
                                $scope.backendUserList = result.data.items;
                                $('#user_modal').modal('hide');
                            }).error(function () {
                            });
                        })
                    }
                }
                if(isFreshlist) {
                    $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/20', {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {
                        $scope.backendUserList = result.data.items;
                        $('#user_modal').modal('hide');
                    }).error(function () {
                    });
                }
            }).error(function (data) {

            });
        };
        //=========================================================

        $scope.updateUser=function(loginId){
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser/findByLoginId/'+loginId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $scope.backendUser = result.data;
                $scope.backendUser.password2 = result.data.password;
                $('#user_modal').modal('show');
                $("#loginId").prop('disabled', true);
                $('#saveButton').hide();
                $('#updateButton').show();
                $scope.popupTitle = "Update the backend User...";
                selectMenu.menu=$('#communities_select');
                selectMenu.clear();
                selectMenu.create(result.data.communities,"selected");
                backendUserCommunityService.get(function(res){
                    for(var i in result.data.communities)
                    {
                        var userComm=result.data.communities[i];
                        for(var j in res.data){
                            var comm=res.data[j];
                            if(userComm.objId==comm.objId)
                            {
                                delete res.data[j];
                                //console.log(comm)
                            }
                        }
                    }
                    selectMenu.create(res.data,"");
                });

                userMenu.menu=$('#user_select');
                userMenu.clear();
                userMenu.create([result.data.appuser],"selected");
                getAllUnbindedServiceUser.get(function(res){
                    userMenu.create(res.data,"");
                });

            }).error(function (result) {
                alert('Error Happened from when trying to get the backend frontendUser information...');
            });
        };

        $scope.saveUpdate=function(loginId,backendUser){
            selectMenu.menu=$('#communities_select');
            backendUser.communities=selectMenu.getValue();
            userMenu.menu=$('#user_select');
            if(userMenu.getValue().length==1){
                backendUser.appuser=userMenu.getValue()[0]
            }else{
                backendUser.appuser=undefined;
            }
            $('#user_modal').modal('hide');
            $http.put('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser/'+loginId, backendUser, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/20', {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (result) {
                    $scope.backendUserList = result.data.items;
                }).error(function () {

                });
            }).error(function (data) {
                alert('Error Happened from when trying to Update the backend frontendUser information...');
            });
        };

        $scope.deleteUser=function(loginId){
            //bootbox.classes.add('medium');
            bootbox.confirm("Are you sure want to delete?", function(result) {
                if(result==true){
                    $http.delete('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminUser/'+loginId, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/adminuser/getAdminUserList/0/20', {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.backendUserList = result.data.items;
                        }).error(function () {
                        });
                    }).error(function (result) {
                        alert('Error Happened from when trying to get the backend frontendUser information...');
                    });
                }
            }).find("div.modal-dialog").css({ width: '30%'});
           // bootbox.alert("Hello").find("div.modal-dialog").addClass("largeWidth");

        }

        $scope.changePassword1Value = function(){
            $scope.matchFlag=true;
        }
        $scope.changePassword2Value = function(){
            $scope.matchFlag=true;
        }
    }]);


angular.module('backofficeApp.backendUser.services', ['ngResource']).
    factory('backendUserCommunityService', function ($resource) {
        return $resource('/rest/v1.0/backoffice/admin/availableCommunities', {}, {});
    }).
    factory('backendUserService',function($resource){
        return $resource('/rest/v1.0/backoffice/admin/createUserForService/:serviceId', {serviceId:'@serviceId'}, {});
    }).
    factory('getAllUnbindedServiceUser',function($resource){
        return $resource('/rest/v1.0/backoffice/admin/getAllUnbindedServiceUser', {}, {});
    })

